package controller

import (
	"ddnser/common/logger"
	"ddnser/service"
	"ddnser/settings"
	"ddnser/utils/errcode"
	"time"

	"github.com/go-co-op/gocron"
	"go.uber.org/zap"
)

type DdnserController struct {
	logger *zap.SugaredLogger
	service.MonitorService
	service.DdnsUpdateService
	service.NotificationService
}

func NewDdnserController(mon service.MonitorService, ddns service.DdnsUpdateService, notification service.NotificationService) *DdnserController {
	return &DdnserController{
		logger.GetLogger(),
		mon,
		ddns,
		notification,
	}
}

func (ddnser *DdnserController) Updator() {
	conf := settings.GetAppConf()
	ips, code := ddnser.Monitor(conf.MonitorConf.Use, conf.MonitorConf.Para)
	if code != errcode.OK {
		return
	}
	// ips = []net.IP{net.ParseIP("2409:8a55:541a:ea30::2")}
	res, code := ddnser.UpdateHost(ips)
	if code == errcode.DDNS_NO_NEED_TO_UPDATE {
		return
	}
	ddnser.NotificationService.Notify(ips, res)
}

func (ddnser *DdnserController) Scheduler() {
	loc, err := time.LoadLocation("Local")
	if err != nil {
		loc, _ = time.LoadLocation("UTC")
	}
	scheduler := gocron.NewScheduler(loc)
	interval := settings.GetAppConf().MonitorConf.Interval
	if interval <= 0 {
		ddnser.Updator()
		return
	}
	_, err = scheduler.Every(interval).Minutes().Do(ddnser.Updator)
	if err != nil {
		ddnser.logger.Errorf("ddnser.scheduler err:%v", err)
		return
	}
	scheduler.StartBlocking()
}
